package com.yunqiao.service.api.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunqiao.common.consts.AppConsts;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.pay.AliPay;
import com.yunqiao.common.pay.WxPay;
import com.yunqiao.common.utils.GeTuiUtils;
import com.yunqiao.common.utils.PageUtils;
import com.yunqiao.common.utils.Query;
import com.yunqiao.service.api.ComplaintService;
import com.yunqiao.service.api.entity.*;
import com.yunqiao.service.api.mapper.*;
import com.yunqiao.service.api.vo.ComplaintVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("complaintService")
public class ComplaintServiceImpl extends ServiceImpl<ComplaintMapper, ComplaintEntity> implements ComplaintService {

    @Resource
    private ComplaintMapper complaintMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private FundDetailMapper fundDetailMapper;
    @Resource
    private MessageMapper messageMapper;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //各种查询条件的过滤,在此进行
        QueryWrapper<ComplaintEntity> queryWrapper = new QueryWrapper<>();
        if (params.get("status") != null && StringUtils.isNotEmpty(MapUtil.getStr(params, "status"))) {
            queryWrapper.eq("c.status", MapUtil.getStr(params, "status"));
        }

        if (StringUtils.isNotEmpty(MapUtil.getStr(params, "createTime")) && StringUtils.isNotEmpty(MapUtil.getStr(params, "updateTime"))) { //当开始时间用
            queryWrapper.between("c.create_time", DateUtil.parse(MapUtil.getStr(params, "createTime"), "yyyy-MM-dd"), DateUtil.parse(MapUtil.getStr(params, "updateTime"), "yyyy-MM-dd"));
        }
        IPage<ComplaintVo> page = this.complaintMapper.pageList(new Query<ComplaintEntity>(params).getPage(),queryWrapper);
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveComplaint(ComplaintEntity complaint) {
        Integer count = complaintMapper.selectCount(new QueryWrapper<ComplaintEntity>()
            .eq("order_id", complaint.getOrderId())
            .eq("user_id", complaint.getUserId()));

        if (count > 0) {
            throw new CustomApiException("你已经投诉过了");
        }

        this.complaintMapper.insert(complaint);
        OrderEntity orderEntity = orderMapper.selectById(complaint.getOrderId());
        orderEntity.setComplaintId(complaint.getId().intValue());
        orderMapper.updateById(orderEntity);

        //给被投诉人发一条推送
        UserEntity userEntity = userMapper.selectById(complaint.getTargetUserId());
        List<String> targetList = new ArrayList<>();
        targetList.add(userEntity.getCliendId());
        GeTuiUtils.send(AppConsts.USER_ROLE_TYPE_2, "被投诉", "您被投诉了！", "您被投诉了！", targetList);
        // 发送消息
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setIsRead(AppConsts.MESSAGE_READ_1);
        messageEntity.setContent("您被投诉了");
        messageEntity.setOrderId(orderEntity.getId());
        messageEntity.setTitle("您被投诉了");
        messageEntity.setTargetUserId(userEntity.getId());
        messageEntity.setUserId(complaint.getUserId().longValue());
        messageMapper.insert(messageEntity);
    }

    @Override
    public ComplaintVo details(Integer id) {
        ComplaintVo complaintVo = complaintMapper.details(id);
        return complaintVo;
    }

    @Override
    public void updateComplain(ComplaintEntity complaint) throws Exception {
        Long id = complaint.getId();
        BigDecimal amount = complaint.getAmount();
        Integer status = complaint.getStatus();
        if (status != null) {
            if (status.equals(AppConsts.COMPLAIN_STATUS_2)) {
                //同意  需要退款给用户
                complaint = complaintMapper.selectById(id);
                OrderEntity orderEntity = orderMapper.selectById(complaint.getOrderId());
                if (amount.doubleValue() > orderEntity.getPrice().doubleValue()) {
                    throw new CustomApiException("输入的金额大于订单金额");
                }

                UserEntity userEntity = userMapper.selectById(orderEntity.getUserId());
                if (orderEntity.getType().equals(AppConsts.PAY_TYPE_1)) {
                    //支付宝退款
                    Boolean flag = AliPay.refund(orderEntity.getOrderNumber(), amount.toString(), RandomUtil.randomNumbers(20), userEntity.getRoleType());
                    //支付宝没有回调，直接在这里改变成功状态
                    if (!flag) {
                        throw new CustomApiException("退款申请失败");
                    }
                } else if (orderEntity.getType().equals(AppConsts.PAY_TYPE_2)) {
                    //微信退款
                    String refund = WxPay.refund(orderEntity.getOrderNumber(), RandomUtil.randomNumbers(20), orderEntity.getPrice().toString(), amount.toString(), userEntity.getRoleType(),null);
                    JSONObject jsonObject = JSONUtil.parseObj(refund);
                    if (!jsonObject.getStr("return_code").equals("SUCCESS")) {
                        throw new CustomApiException("退款申请失败");
                    }
                } else if (orderEntity.getType().equals(AppConsts.PAY_TYPE_3)) {
                    //余额退款
                    orderEntity.setStatus(AppConsts.ORDER_STATUS_10);
                    int i = 0;
                    do {
                        userEntity = userMapper.selectById(userEntity.getId());
                        i = userMapper.updateBalance(userEntity.getId(), userEntity.getBalance().add(amount), userEntity.getBlockBalance(), userEntity.getVersion());
                    } while (i == 0);
                }
                //生成流水
                FundDetailEntity fundDetail = new FundDetailEntity();
                fundDetail.setAmount(amount);
                fundDetail.setCreateTime(new Date());
                fundDetail.setRelateId(orderEntity.getId().intValue());
                fundDetail.setRemark(orderEntity.getRemark());
                fundDetail.setTypeFrom(7);
                fundDetail.setTypeChange(AppConsts.FUND_DETAIL_TYPE_2);
                fundDetail.setUserId(orderEntity.getUserId().intValue());
                fundDetail.setRemark("投诉退款");
                fundDetailMapper.insert(fundDetail);
                //扣除司机账户
                int i = 0;
                do {
                    userEntity = userMapper.selectById(orderEntity.getDriverId());
                    //退款的金额直接在司机余额里扣除
                    i = userMapper.updateOrderBlockBalance(userEntity.getId(), userEntity.getBalance().subtract(amount), userEntity.getOrderBlockBalance(), userEntity.getVersion());
                } while (i == 0);
                complaint.setStatus(AppConsts.COMPLAIN_STATUS_2);
            } else if (status.equals(AppConsts.COMPLAIN_STATUS_3)) {
                //拒绝 没有业务逻辑
                complaint.setStatus(AppConsts.COMPLAIN_STATUS_3);
            }
        }

        complaintMapper.updateById(complaint);
    }
}
